import { vbenConfig } from "../../vbenConfig"
import { IJson, IField, IResAndReqFields, IEnumObj, IResAndReqFieldsMap } from "../../interface/type"
import { SwResult } from "../../store/swResult"
import utilTool from "../../util/tool"

const STATIC_DEF = "#/definitions/"

const COMP_NAMES = {
  select: 'Select',
  number: 'InputNumber',
  date: 'DatePicker',
  rangeDate: 'RangePicker',
  month: 'MonthPicker',
  input: 'Input',
  switchComp: 'Switch',
  cascader: 'Cascader',
  checkGroup: 'CheckboxGroup',
  radioGroup: 'RadioGroup',
  upload: 'Upload',
  apiSearchSelect: 'ApiSearchSelect',
  apiTreeSelect: 'ApiTreeSelect'
}

// 获取枚举名
function getEnumName (name: string): string {
  const basePath = vbenConfig.baseUrl.replace(/\//g, '')
  return utilTool.firstUp(basePath) + utilTool.firstUp(name) + 'Enum'
}

function getEnumOption(item: IJson): IEnumObj {
  // 如果是枚举
  let enumOjb: IEnumObj = {}
  const description = utilTool.trimStr(item?.description)
  if (description.indexOf('：') > -1) {
    enumOjb = utilTool.handleOldRuleEnum(description, item.enum)
  } else if (description.indexOf(': ') > -1) {
    enumOjb = utilTool.handleBlankEnum(description, item.enum)
  } else {
    enumOjb = utilTool.handleEnum(description, item.enum)
  }
  return enumOjb
}

function getType(field: IField, name: string): string {
  let type: string = 'any'
  switch (field.type) {
    case 'integer':
    case 'number':
      type = 'number';
      break;
    case 'boolean':
      type = 'boolean';
      break;
    case 'string':
      type = 'string';
      break;
    case 'array': {
      if (field.children && field.children.length > 0) {
        const childrenName: string = utilTool.firstUp(field.name)
        type = childrenName ? `I${childrenName}[]` : `I${name}[]`;
      } else {
        type = field.childrenType ? `I${field.childrenType}[]` : `I${name}[]`;
      }
      break;
    }
    case 'object': {
      if (field.children && field.children.length > 0) {
        const childrenName: string = utilTool.firstUp(field.name)
        type = childrenName ? `I${childrenName}` : `I${name}`;
      }
      break;
    }
    case 'date':
      type = 'string';
      break;
    default: {
      if (field.children && field.children.length > 0) {
        const childrenName: string = utilTool.firstUp(field.name)
        type = childrenName ? `I${childrenName}` : `I${name}`;
      }
      break;
    }
  }
  return type
}

function findSingleProperty(name: string, item: IJson, requiredPrams: string[], definitions: IJson, ref: string): IField {
  const obj: IField = {
    name, // 名称
    type: item.type, // 类型
    description: item.description, // 描述
    isEnum: ((item.enum && item.enum.length > 0) ? true : false), // 是否是枚举
    // component?: string; // 组件名
  }
  if (item.format) {
    obj.format = item.format
  }
  if (obj.isEnum) {
    // 处理枚举
    const iEnum = getEnumOption(item)
    obj.description = iEnum.description
    obj.EnumOptions = iEnum.enums
    obj.EnumOptionName = getEnumName(name) // 枚举的名称
  }
  // obj[key] = item
  if (requiredPrams.indexOf(name) > -1 || item.required) {
    obj.isReq = true
  }
  if (item && (item.type === "array" || item.type === "object") && (!!item?.$ref || !!item?.items?.$ref)) {
    const refs = item?.$ref ? item.$ref : item?.items?.$ref
    console.log('查找下一层', refs)
    if (refs === ref) {
      obj.children = findDefinition(refs, definitions)
    }
    obj.childrenRef = refs
  } else if (item && !item.type && item?.$ref) {
    console.log('查找下一层--->', item.$ref)
    if (item.$ref === ref) {
      obj.children = findDefinition(item.$ref, definitions)
    }
    obj.childrenRef = item.$ref
  } else if (item && (item.type === "array") && item.items.type) {
    obj.childrenFormat = item.items.format
    obj.childrenType = item.items.type
  }
  return obj
}

function findDefinition(ref: string, definitions: IJson): IField[] {
  console.log('查找列表对象', ref)
  // const obj: IField = { name: '' }
  const arr: IField[] = []
  if (!ref || ref === STATIC_DEF) {
    return arr
  }
  ref = ref.replace(STATIC_DEF, "")
  // console.log('查找对象:', definitions[ref])
  const properties = definitions[ref]?.properties
  if (ref.indexOf('响应结果') > -1) {
    if (properties.data && properties.data.type === 'array') {
      ref = properties.data.items?.$ref
    } else if (properties.data && properties.data.type === 'object' && properties.data.item?.$ref) {
      ref = properties.data.item?.$ref
    } else {
      ref = properties.data?.$ref ? properties.data?.$ref : ''
    }
    return findDefinition(ref, definitions)
  }
  // 必填字段
  const requiredPrams: string[] = definitions[ref]?.required ? definitions[ref]?.required : []

  for (const key of Object.keys(properties)) {
    const item = properties[key]
    arr.push(findSingleProperty(key, item, requiredPrams, definitions, ref))
  }
  console.log('-------------->', arr)
  return arr
  // return findProperties(properties, requiredPrams, definitions)
}

// 获取参数并格式化字段
function getParameters(parameters: IJson[], definitions: IJson): IField[] {
  const arr: IField[] = []
  if (!parameters || parameters.length === 0) return arr
  // 如果参数采用有是body的模式
  if (parameters[0].in === 'body') {
    if (parameters[0].name === 'request') {
      return findDefinition(parameters[0]?.schema?.$ref, definitions)
    } else if (!parameters[0]?.schema?.$ref) {
      // 如果参数是数组，比如:ids
      const item = parameters[0]
      item.items = item.schema.items
      item.type = item.schema.type
      arr.push(findSingleProperty(item.name, item, [], definitions, ''))
    }
  } else {
    for (const item of parameters) {
      arr.push(findSingleProperty(item.name, item, [], definitions, ''))
    }
  }
  return arr
}

function getResult(apiName: string, sw: SwResult): IResAndReqFields {
  const paths = sw.getPaths()
  // pageConfig?.list?.apiName
  const item = paths[apiName]
  if (!item) {
    return {
      request: [],
      response: []
    }
  }
  const json = item.post ? item.post : item.get
  const parameters = json.parameters
  const responses = json.responses['200']
  const parma: IField[] = getParameters(parameters, sw.getDefinitions())
  // console.log('接口入参：', parma)
  if (responses.schema?.type && responses.schema.type === 'array') {
    const res: IField[] = findDefinition(responses.schema.items?.$ref, sw.getDefinitions())
    // console.log('接口出参：', res)
    return {
      request: parma, // 请求参数
      response: res, // 请求结果
      responseType: 'array'
    }
  } else {
    const res: IField[] = findDefinition(responses.schema.$ref, sw.getDefinitions())
    // console.log('接口出参：', res)
    return {
      request: parma, // 请求参数
      response: res // 请求结果
    }
  }
}

function getAllEnums(json: IResAndReqFieldsMap): IJson {
  const enums: IJson = {}
  for (const key of Object.keys(json)) {
    const item: IResAndReqFields = json[key]
    for (const field of item.request) {
      if (field.isEnum && field.EnumOptionName) {
        enums[field.EnumOptionName] = {
          enums: field.EnumOptions, // 枚举
          description: field.description // 描述
        }
      }
    }

    for (const field of item.response) {
      if (field.isEnum && field.EnumOptionName) {
        enums[field.EnumOptionName] = {
          enums: field.EnumOptions, // 枚举
          description: field.description // 描述
        }
      }
    }
  }
  return enums
}

// 根据规则生成组件以及组件参数配置
function updateCompProp(item: IField): void {
  console.log('item >>> ', item)
  // const upServerName = firstLower(lineToUp(swaggerConfig.serverName))
  item.description = utilTool.getNameFromDesc(item.description)
  item.compProps = ''
  if (item?.EnumOptions && item?.EnumOptions?.length > 0) {
    // 枚举
    item.component = COMP_NAMES.select
    item.compProps = `componentProps: {
        options: enumsToOption(${item.EnumOptionName})
      },
    `
    return
  }
  // 可以这里根据与后台的约定，输入对应的组件以及组件属性
  if (utilTool.checkStrIncludeKeyWord(item.description, ['类型', '状态'])) {
    item.component = COMP_NAMES.select
    item.compProps = `componentProps: {
        options: enumsToOption(${item.EnumOptionName})
      },
    `
    return
  }
  item.type = ('' + item.type).toLowerCase()
  // 在这里可以根据描述，来指定对应的组件
  switch (item.type) {
    case 'bigdecimal':
      item.component = COMP_NAMES.number
      break
    case 'long':
    case 'integer': {
      // 一般来说搜索条件integer型是ＩＤ或编号类 [这里根据自己的项目，订制相应的组件]
      if (utilTool.checkStrIncludeKeyWord(item.description, ['量', '值', '数'])) {
        item.component = COMP_NAMES.number
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['城市'])) {
        item.component = COMP_NAMES.apiTreeSelect
        item.compProps = `componentProps: {
          allowClear: true,
          params: {
            flag: true, // 是否返回树形结构，true -> 是，false -> 否
            level: 2, // 地址层级
          },
          api: listAddressByLevel,
          replaceFields: {
            label: 'name',
            key: 'code',
            value: 'code',
            children: 'addresses',
          },
          value: 'code',
          dropdownStyle: {
            maxHeight: '400px',
            overflow: 'auto',
          },
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['金额'])) {
        item.component = COMP_NAMES.number
        item.compProps = `componentProps: {
          precision: 2,
          min: 0,
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['员工', '创建人']) || item.name === 'userId' || item.name === 'staffCode') {
        item.component = COMP_NAMES.apiSearchSelect
        item.compProps = `componentProps: {
          options: []
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['图片'])) {
        item.component = COMP_NAMES.upload
        item.compProps = `componentProps: {
          isEdit: false,
          baseColProps: {
            span: 24
          }
        }`
      } else {
        item.component = COMP_NAMES.select
        item.compProps = `componentProps: {
          options: []
        },
        `
      }
      break
    }
    case 'string': {
      if (item.format === 'date-time') {
        item.component = COMP_NAMES.date
        item.compProps = `componentProps: {
          showTime: false,
          // disabledDate: (current) => {
          //  // Can not select days before today and today
          //  return current && current < dateUtil().startOf('day');
          // },
        },
        // defaultValue: [dateUtil().add(-7, 'days').startOf('day'), dateUtil().endOf('day')],
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['月份'])) {
        item.component = COMP_NAMES.month
        item.compProps = `componentProps: {
          type: 'month',
          placeholder: '请选择${ item.description}',
          valueFormat: 'yyyy-MM'
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['金额'])) {
        item.component = COMP_NAMES.number
        item.compProps = `componentProps: {
          precision: 2,
          min: 0,
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['城市'])) {
        item.component = COMP_NAMES.select
        item.compProps = `componentProps: {
          options: []
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['公司'])) {
        item.component = COMP_NAMES.select
        item.compProps = `componentProps: {
          filterable: true,
          options: []
        },
        `
      } else if (utilTool.checkStrIncludeKeyWord(item.description, ['组织'])) {
        item.component = COMP_NAMES.cascader
        item.compProps = `componentProps: {
          options: [],
          changeOnSelect: true,
        },
        `
      } else {
        item.component = COMP_NAMES.input
        item.compProps = `componentProps: {
          placeholder: '请输入${ item.description}',
          maxLength: 50 // 可以设置默认最大长度
        },
        `
      }
      break
    }
    case 'boolean':
      item.component = COMP_NAMES.switchComp
      break
    case "number":
      item.component = COMP_NAMES.number
      item.compProps = `componentProps: {
        precision: 2,
        min: 0,
      },
      `
      break
    default: {
      item.component = COMP_NAMES.input
      item.compProps = `componentProps: {
        placeholder: '请输入${ item.description}',
        maxLength: 50 // 可以设置默认最大长度
      },
      `
      break
    }
  }
  // 如果是必填
  if (item.isReq) {
    const resType = item.component === COMP_NAMES.select ? '选择' : '输入'
    item.isReq = true
    item.compProps = item.compProps + `
    dynamicRules: () => {
      return [
        {
          required: true,
          validator: (_, value) => {
            if (!value) {
              return Promise.reject('请${resType}${item.description}');
            }
            return Promise.resolve();
          },
        },
      ];
    },
    `
  }
}

export default {
  findDefinition,
  getResult,
  getType,
  getAllEnums,
  updateCompProp
}
